from flask import Flask,request,render_template,jsonify
from flask_cors import CORS
import pymysql
import json
from connects import Mysql
from onenet import onenet
from User import Mysql_User
from captcha import CreatCaptcha
from Meil import Mail
from addr import Mysql_Addr
app = Flask(__name__)
onenets = onenet()
deviceId = "755493629"
APIKey = "HFUwXTTVeKPk1H3p=qjAUyMvSuM="
infoId = [deviceId,APIKey]
CORS(app, supports_credentials=True) #解决跨域问题
@app.route("/info",methods=['GET','POST'])
def info():
    db = Mysql()
    result = db.getdata()
    results = []
    content = {}
    for num in result:
        content = {"id":num[0],"username":num[1],"password":num[2],"gender":num[3]}
        results.append(content)
        content={}
    print(results)
    return json.dumps(results)
@app.route("/update",methods=['GET','POST'])

def update():
    print("nextOne")
    if request.method == "POST":
        result = request.get_json()
        postForm = json.loads(request.get_data(as_text=True))
        print(postForm)
        print(result)
        print(request.get_data())
        print(request.get_json())
        db = Mysql()
        db.updatedate(result)
        return "ok"
    else:
        return "请用POST方法"

@app.route("/getOneNet",methods=['GET','POST'])

def getOneNet():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_Addr()
        deviceId = result["deviceIds"]
        APIKey = result["APIKeys"]
        infoId = [deviceId,APIKey]
        print(infoId)
        try:
            date = onenets.OneNet_get_data(infoId)
            print(date)
            db.addOne(date[4]["current_value"],date[5]["current_value"],result["user_id"],date[4]["update_at"])
            return json.dumps(date)
        except:
            return "数据不正常"
    else:
        return "请使用POST方法"
@app.route("/delete",methods=['GET','POST'])

def delete_data():
    if request.method == "POST":
        result = request.get_json()
        print( result["id"])
        db = Mysql()
        db.delete(result["id"])
        return "ok"
    else:
        return "请使用POST方法"
@app.route("/insert",methods=['GET','POST'])

def insert_data():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql()
        db.insert(result["username"],result["password"],result["gender"])
        return "ok"
    else:
        return "请使用POST方法"
@app.route("/select_username",methods=['GET','POST'])

def select_username():
    result = request.get_json()
    print(result)
    db = Mysql()
    results = db.select_usernaem(result["username"])
    list = []
    for num in results:
        one = {"id":num[0],"username":num[1],"password":num[2],"gedner":num[3]}
        list.append(one)
    print(list)
    return json.dumps(list)
@app.route("/login",methods=['GET','POST'])

def login():
    if request.method == "POST":
        db = Mysql_User()
        results = db.login()
        result = request.get_json()
        msg = []
        user = result["user"]
        pwd = result["pwd"]
        print(results)
        for users in results:
            if user == users[1] and pwd == users[2]:
                msg.append(users)
                return json.dumps(users)
        return "error"
    else:
        return "请使用POST方法"

@app.route("/legist",methods=['GET','POST'])

def legist():
    if request.method == "POST":
        result = request.get_json()
        db = Mysql_User()
        db.legist(result["user"],result["pwd"],result["apiKey"],result["userStatus"],result["accessId"],result["email"],result["phone"])
        print(result)
        return "ok"
    else:
        return "请使用POST方法"
@app.route("/getCaptcha",methods=['GET','POST'])

def getCaptcha():
    if request.method == "POST":
        result = request.get_json()
        db = Mysql_User()
        captchas = CreatCaptcha()
        mail = Mail()
        results = db.getEmail(result["user"])
        for email in results:
            print(email[6])
            if email[6] == result["email"]:
                #生成验证码、发送到邮箱、返回验证码
                captcha = captchas.captcha(6)
                mail.sendMail(email[6],captcha)
                return captcha
        return "error"
    else:
        return "请使用POST方法"

@app.route("/changePwd",methods=['GET','POST'])

def changePwd():
    if request.method == "POST":
        result = request.get_json()
        db = Mysql_User()
        db.changePwd(result["pwd"],result["user"])
        print(result)
        return "ok"
    else:
        return "请使用POST方法"

@app.route("/changeInfo",methods=['GET','POST'])

def changeInfo():
    if request.method == "POST":
        result = request.get_json()
        db = Mysql_User()
        db.changeInfo(result["user"],result["psw"],result["Email"],result["phone"])
        print(result)
        return "ok"
    else:
        return "请使用POST方法"
@app.route("/selectAll",methods=['GET','POST'])

def selectAll():
    if request.method == "POST":
        db = Mysql_User()
        result = db.selectAll()
        return json.dumps(result)
    else:
        return "请使用POST方法"
@app.route("/changeOneInfo",methods=['GET','POST'])

def changeOneInfo():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_User()
        db.changeOneInfo(result["name"],result["pwd"],result["apiKey"],result["status"],result["accessId"],result["email"],result["phone"],result["id"])
        return "ok"
    else:
        return "请使用POST方法"

@app.route("/deleteById",methods=['GET','POST'])

def deleteById():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_User()
        addr = Mysql_Addr()
        db.deleteById(result["Id"])
        # addr.deleteByUser(result["Id"])
        return "ok"
    else:
        return "请使用POST方法"

@app.route("/selectByName",methods=['GET','POST'])

def selectByName():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_User()
        data = db.selectByname(result["name"])
        return json.dumps(data)
    else:
        return "请使用POST方法"

@app.route("/addNew", methods=['GET', 'POST'])

def addNew():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_User()
        db.addNew(result["name"],result["pwd"],result["apiKey"],result["statue"],result["accessId"],result["email"],result["phone"])
        return "ok"
    else:
        return "请使用POST方法"

@app.route("/getAllAddr", methods=['GET', 'POST'])

def getAllAddr():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_Addr()
        data = db.getAllAddr(result["user_id"])
        print(data)
        return json.dumps(data)
    else:
        return "请使用POST方法"

@app.route("/selectAllAddr", methods=['GET', 'POST'])

def selectAllAddr():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_Addr()
        data = db.selectAllAddr()
        print(data)
        return json.dumps(data)
    else:
        return "请使用POST方法"

@app.route("/changeAddr", methods=['GET', 'POST'])

def changeAddr():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_Addr()
        db.changeAddr(result["id"],result["userId"],result["long"],result["lant"],result["time"])
        return "ok"
    else:
        return "请使用POST方法"

@app.route("/deleteAddrById", methods=['GET', 'POST'])

def deleteAddrById():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_Addr()
        db.deleteAddrById(result["id"])
        return "ok"
    else:
        return "请使用POST方法"

@app.route("/selectAddrByUserId", methods=['GET', 'POST'])

def selectAddrByUserId():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_Addr()
        data = db.selectAddrByUserId(result["userId"])
        print(data)
        return json.dumps(data)
    else:
        return "请使用POST方法"

@app.route("/addNewAddr", methods=['GET', 'POST'])

def addNewAddr():
    if request.method == "POST":
        result = request.get_json()
        print(result)
        db = Mysql_Addr()
        db.addNewAddr(result["userId"],result["lon"],result["lat"],result["time"])
        return "ok"
    else:
        return "请使用POST方法"

if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0',port="5001")